package com.mbuswidget;

import android.app.Activity;
import android.app.AlertDialog;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Messenger;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MBusWidgetConfigurationStopsAddStopByRoute extends Activity {
	private Integer widgetID = AppWidgetManager.INVALID_APPWIDGET_ID;
	private MBusWidgetService mbusBoundService;
	
	private MBusInfo mbusInfo;

	/** Messenger for communicating with service. */
	Messenger mService = null;

	public MBusWidgetConfigurationStopsAddStopByRoute() {
		super();
	}

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			// This is called when the connection with the service has been
			// established, giving us the service object we can use to
			// interact with the service. Because we have bound to a explicit
			// service that we know is running in our own process, we can
			// cast its IBinder to a concrete class and directly access it.
			mbusBoundService = ((MBusWidgetService.LocalBinder) service)
					.getService();
			// mService = new Messenger((MBusWidgetService.LocalBinder)service);

			// Tell the user about this for our demo.
//			Toast.makeText(MBusWidgetConfigurationStopsAddStopByRoute.this,
//					R.string.local_service_connected, Toast.LENGTH_SHORT)
//					.show();

			ShowResults();
		}

		public void onServiceDisconnected(ComponentName className) {
			// This is called when the connection with the service has been
			// unexpectedly disconnected -- that is, its process crashed.
			// Because it is running in our same process, we should never
			// see this happen.
			mbusBoundService = null;

			// This is called when the connection with the service has been
			// unexpectedly disconnected -- that is, its process crashed.
			mService = null;

//			Toast.makeText(MBusWidgetConfigurationStopsAddStopByRoute.this,
//					R.string.local_service_disconnected, Toast.LENGTH_SHORT)
//					.show();
		}
	};
	private boolean mIsBound;

	void doBindService() {
		// Establish a connection with the service. We use an explicit
		// class name because we want a specific service implementation that
		// we know will be running in our own process (and thus won't be
		// supporting component replacement by other applications).
		bindService(
				new Intent(MBusWidgetConfigurationStopsAddStopByRoute.this, MBusWidgetService.class),
				mConnection, Context.BIND_AUTO_CREATE);
		mIsBound = true;
	}

	void doUnbindService() {
		if (mIsBound) {
			// Detach our existing connection.
			unbindService(mConnection);
			mIsBound = false;
		}
	}


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.selectstopby);
		setResult(RESULT_CANCELED);

		widgetID = getIntent().getIntExtra(
				AppWidgetManager.EXTRA_APPWIDGET_ID,
				AppWidgetManager.INVALID_APPWIDGET_ID);
		
		if(widgetID == AppWidgetManager.INVALID_APPWIDGET_ID) {
			finish();
		}
		
		TextView topLabel = (TextView)findViewById(R.id.Toplbl);
		topLabel.setText(R.string.chooseRoute);
		
        //Log.w("mbuswidget", "Creating widget with id: " + widgetID);
        
		mIsBound = false;

		// startService(new Intent(MBusWidgetActivity.this,
		// MBusWidgetService.class));

		doBindService();
	}

	private void ShowResults() {
		mbusInfo = null;

		if (mbusBoundService != null) {
			mbusInfo = mbusBoundService.getBusInfo();
		}

		if (mbusInfo == null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Cannot connect to MBus XML server")
					.setCancelable(true);
			AlertDialog alert = builder.create();
			alert.show();
			// System.exit(0);
		} else {
			// int numOfRoutes = mBusInfoDoc.getElementsByTagName("livefeed")
			// .getLength();
			ListView lv = (ListView) findViewById(R.id.itemList);

			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1);
			lv.setAdapter(adapter);

			for (int i = 0; i < mbusInfo.getRoutes().size(); i++) {
				adapter.add(mbusInfo.getRoutes().get(i).getName());
			}

			lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				public void onItemClick(AdapterView<?> av, View v, int pos,
						long id) {

					Intent intent = new Intent(MBusWidgetConfigurationStopsAddStopByRoute.this,
							MBusWidgetConfigurationStopsAddStopByRouteStop.class);
					intent.putExtra(MBusWidgetConstants.SELECTED_ROUTE, (int)id);
					intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetID);

					startActivityForResult(intent, 0);
				}
			});
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case (0): {
			if (resultCode == Activity.RESULT_OK) {
				// We have information required. Complete Widget setup.
				
				String[] stopsArray = data.getExtras().getStringArray(MBusWidgetConstants.INTENT_SELECTED_STOPS);
				
				Intent intent =  new Intent(MBusWidgetConfigurationStopsAddStopByRoute.this, MBusWidgetConfigurationStopsAddStop.class);
				intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetID);

				intent.putExtra(MBusWidgetConstants.INTENT_SELECTED_STOPS,
						stopsArray);
			
				setResult(RESULT_OK, intent);
				doUnbindService();
				finish();
			}
			break;
		}
		}
	}
}